"""
日志管理模块

提供统一的日志管理功能
"""

import logging
import logging.config
import sys
from pathlib import Path
from typing import Any, Dict, Optional

from axiom_boot.conf.manager import Settings


def setup_logging(settings: Settings) -> None:
    """
    设置日志配置。
    直接使用从 Settings 实例获取的 dictConfig。
    """
    log_config = settings.get_logging_config()
    
    # 确保日志文件目录存在
    if 'file' in log_config.get('handlers', {}):
        log_filename = log_config['handlers']['file'].get('filename')
        if log_filename:
            Path(log_filename).parent.mkdir(parents=True, exist_ok=True)
            
    logging.config.dictConfig(log_config)

    # 为关键的第三方库设置更高级别的日志，以减少干扰
    third_party_levels = {
        "uvicorn": logging.INFO,
        "sqlalchemy": logging.WARNING,
        # 最终修正：将 dashscope 的日志级别提升至 INFO，
        # 以屏蔽其打印的、包含巨量向量数据的 DEBUG 级请求日志。
        "dashscope": logging.INFO,
    }
    # 允许用户在配置中覆盖默认值
    for logger_name, level_name in settings.log_third_party_levels.items():
        logging.getLogger(logger_name).setLevel(level_name.upper())
    
    logger = get_logger(__name__)
    logger.info("Logging configured successfully.")


def get_logger(name: str) -> logging.Logger:
    """获取日志记录器
    
    Args:
        name: 日志记录器名称
    
    Returns:
        日志记录器实例
    """
    return logging.getLogger(name)


def set_log_level(level: str) -> None:
    """设置日志级别
    
    Args:
        level: 日志级别
    """
    logging.getLogger().setLevel(getattr(logging, level.upper()))


def add_file_handler(logger_name: str, file_path: str, level: str = "INFO") -> None:
    """添加文件处理器
    
    Args:
        logger_name: 日志记录器名称
        file_path: 文件路径
        level: 日志级别
    """
    logger = logging.getLogger(logger_name)
    
    # 创建文件处理器
    file_handler = logging.FileHandler(file_path, encoding='utf-8')
    file_handler.setLevel(getattr(logging, level.upper()))
    
    # 创建格式化器
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )
    file_handler.setFormatter(formatter)
    
    # 添加处理器
    logger.addHandler(file_handler)


def remove_handler(logger_name: str, handler_class: type) -> None:
    """移除处理器
    
    Args:
        logger_name: 日志记录器名称
        handler_class: 处理器类
    """
    logger = logging.getLogger(logger_name)
    
    # 找到并移除指定类型的处理器
    handlers_to_remove = []
    for handler in logger.handlers:
        if isinstance(handler, handler_class):
            handlers_to_remove.append(handler)
    
    for handler in handlers_to_remove:
        logger.removeHandler(handler)


class LoggerMixin:
    """日志记录器混入类
    
    为类提供日志记录功能
    """
    
    @property
    def logger(self) -> logging.Logger:
        """获取日志记录器"""
        return get_logger(self.__class__.__name__)
    
    def log_info(self, message: str, *args, **kwargs):
        """记录信息日志"""
        self.logger.info(message, *args, **kwargs)
    
    def log_warning(self, message: str, *args, **kwargs):
        """记录警告日志"""
        self.logger.warning(message, *args, **kwargs)
    
    def log_error(self, message: str, *args, **kwargs):
        """记录错误日志"""
        self.logger.error(message, *args, **kwargs)
    
    def log_debug(self, message: str, *args, **kwargs):
        """记录调试日志"""
        self.logger.debug(message, *args, **kwargs)
    
    def log_exception(self, message: str, *args, **kwargs):
        """记录异常日志"""
        self.logger.exception(message, *args, **kwargs) 